package com.copyctrl.campus.portal.controller;

import cn.hutool.json.JSONUtil;
import com.copyctrl.campus.common.domain.ScrollResult;
import com.copyctrl.campus.common.model.ApiResponse;
import com.copyctrl.campus.portal.dto.CommentDTO;
import com.copyctrl.campus.portal.dto.PassageDTO;
import com.copyctrl.campus.portal.service.CommentService;
import com.copyctrl.campus.portal.service.PassageService;
import com.copyctrl.model.CampKind;
import com.copyctrl.model.CampPassage;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author:JH
 * @version:1.0
 * page是偏移量 不是页码
 */
@RestController
@RequestMapping("/passage")
public class PassageController {
    @Resource
    PassageService passageService;
    @Resource
    CommentService commentService;

    @GetMapping("/kind")
    public ApiResponse getAllKinds(){
        List<CampKind> allKind = passageService.getAllKind();
        return ApiResponse.ofSuccess(allKind);
    }

    @GetMapping("/all/{page}/{max}")
    public ApiResponse getAllPassages(@PathVariable int page,@PathVariable Long max){
        ScrollResult<PassageDTO> allPassages = passageService.getAllPassages(max, page);
        return ApiResponse.ofSuccess(allPassages);
    }

    @GetMapping("/{kind}/{page}/{max}")
    public ApiResponse getByKind(@PathVariable Integer kind,@PathVariable int page,@PathVariable Long max){
        ScrollResult<PassageDTO> byKindId = passageService.getByKindId(kind, page, max);
        return ApiResponse.ofSuccess(byKindId);
    }

    @GetMapping("/detail/{id}")
    public ApiResponse getById(@PathVariable Integer id){
        Map result = new HashMap();
        CampPassage byId = passageService.findById(id);
        result.put("passage",byId);
        List<CommentDTO> byTextId = commentService.findByTextId(id,0)
                .stream()
                .sorted(Comparator.comparing(CommentDTO::getCreateTime).reversed())
                .collect(Collectors.toList());
        result.put("comment",byTextId);
        return ApiResponse.ofSuccess(result);
    }

    @GetMapping("/hot")
    public ApiResponse getHot(){
        List<PassageDTO> hot = passageService.findHot();
        return ApiResponse.ofSuccess(hot);
    }

    @PostMapping("/likes")
    public ApiResponse getLikes(@RequestBody Map<String,List<Integer>> body){
        System.out.println(body);
        List<Integer> list = body.get("list");
        List<PassageDTO> like = passageService.findLike(list);
        return ApiResponse.ofSuccess(like);
    }
}
